package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.Result;
import com.fjh.springboot_01.service.LessonLikeService;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/lesson/like")
public class LessonLikeController {
    @Autowired
    private LessonLikeService lessonLikeService;

    @PostMapping
    public Result like(@RequestBody Map<String, Integer> params) {
        Integer lessonId = params.get("lessonId");
        if (lessonId == null) {
            return Result.error("课程ID不能为空");
        }

        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            lessonLikeService.like(lessonId, userId);
            return Result.success();
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    @DeleteMapping
    public Result unlike(@RequestParam Integer lessonId) {
        if (lessonId == null) {
            return Result.error("课程ID不能为空");
        }

        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            lessonLikeService.unlike(lessonId, userId);
            return Result.success();
        } catch (Exception e) {
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }

    @GetMapping("/status")
    public Result<Boolean> isLiked(@RequestParam Integer lessonId) {
        if (lessonId == null) {
            return Result.error("课程ID不能为空");
        }

        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            boolean isLiked = lessonLikeService.isLiked(lessonId, userId);
            return Result.success(isLiked);
        } catch (Exception e) {
            return Result.error("获取点赞状态失败：" + e.getMessage());
        }
    }

    @GetMapping("/count")
    public Result<Integer> getLikeCount(@RequestParam Integer lessonId) {
        if (lessonId == null) {
            return Result.error("课程ID不能为空");
        }

        try {
            Integer count = lessonLikeService.getLikeCount(lessonId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("获取点赞数量失败：" + e.getMessage());
        }
    }
} 